{% extends 'knowledge/base.html' %}
{% load static %}

{% block title %}编辑文档 - {{ collection_name }} - 知识库管理系统{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'knowledge/css/simplemde.min.css' %}">
<style>
    .metadata-editor { height: 150px; }
    .content-editor { min-height: 300px; }
</style>
{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto">
    <div class="flex items-center mb-6">
        <a href="{% url 'knowledge:collection_detail' collection_name %}" class="text-neutral hover:text-primary mr-4">
            <i class="fa fa-arrow-left"></i>
        </a>
        <div>
            <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">编辑文档</h2>
            <p class="text-neutral mt-1">编辑集合 <span class="font-medium">{{ collection_name }}</span> 中的文档</p>
        </div>
    </div>

    <div class="bg-white rounded-xl p-6 md:p-8 card-shadow">
        <form method="post" class="space-y-6">
            {% csrf_token %}
            <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                <div class="md:col-span-12">
                    <label for="title" class="block text-sm font-medium text-gray-700 mb-1">文档标题 <span class="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" required
                           class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                           placeholder="输入文档标题" value="{{ title }}">
                </div>

                <div class="md:col-span-12">
                    <label for="content" class="block text-sm font-medium text-gray-700 mb-1">文档内容 <span class="text-red-500">*</span></label>
                    <textarea id="content" name="content" required
                              class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary content-editor"
                              placeholder="输入文档内容...">{{ content }}</textarea>
                </div>

                <div class="md:col-span-12">
                    <label class="block text-sm font-medium text-gray-700 mb-1">元数据</label>
                    <div class="mb-2">
                        <table class="w-full" id="metadata-table">
                            <thead>
                                <tr>
                                    <th class="text-left pb-2 w-5/12">键</th>
                                    <th class="text-left pb-2 w-5/12">值</th>
                                    <th class="text-left pb-2 w-2/12"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 表格行将通过JavaScript动态生成 -->
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="flex justify-start mb-2">
                        <button type="button" id="add-row" class="flex items-center px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm">
                            <i class="fa fa-plus mr-1"></i> 添加字段
                        </button>
                    </div>
                    
                    <!-- 隐藏的JSON输入框，用于表单提交 -->
                    <input type="hidden" id="metadata" name="metadata" value="{{ metadata }}">
                    <p class="mt-1 text-xs text-neutral">添加键值对形式的元数据，系统会自动更新标题到元数据中</p>
                    <p id="metadata-error" class="mt-1 text-xs text-red-500 hidden">元数据格式有误，请检查输入</p>
                </div>
            </div>

            <div class="pt-4 flex justify-between border-t border-gray-100">
                <div>
                    <span class="text-sm text-neutral">文档ID: <code class="bg-gray-100 px-2 py-1 rounded text-xs">{{ document_id }}</code></span>
                </div>
                <div class="space-x-3">
                    <a href="{% url 'knowledge:collection_detail' collection_name %}" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                        取消
                    </a>
                    <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-sm">
                        更新文档
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'knowledge/js/simplemde.min.js' %}"></script>
<script>
// 初始化Markdown编辑器
var simplemde = new SimpleMDE({
  element: document.getElementById("content"),
  spellChecker: false,
  toolbar: [
    "bold", "italic", "strikethrough", "|",
    "heading-1", "heading-2", "heading-3", "|",
    "code", "quote", "unordered-list", "ordered-list", "link","|",
    "preview", "fullscreen", "guide","side-by-side"
  ]
});

// 添加表单验证
 document.querySelector('form').addEventListener('submit', function(e) {
    if (!simplemde.value().trim()) {
        e.preventDefault();
        alert('文档内容不能为空');
        // 聚焦到编辑器
        document.querySelector('.CodeMirror').focus();
    }
});

// <script>
// 获取元素
const metadataInput = document.getElementById('metadata');
const metadataError = document.getElementById('metadata-error');
const metadataTable = document.getElementById('metadata-table');
const addRowBtn = document.getElementById('add-row');
const form = metadataInput.closest('form');

// 添加新行
function addNewRow(key = '', value = '') {
    const tbody = metadataTable.querySelector('tbody');
    const newRow = document.createElement('tr');
    newRow.className = 'metadata-row';
    newRow.innerHTML = `
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-key w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="键名" value="${key}">
        </td>
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-value w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="值" value="${value}">
        </td>
        <td class="pb-2 text-center">
            <button type="button" class="delete-row px-2 py-1 text-red-500 hover:text-red-700 rounded-lg" title="删除行">
                <i class="fa fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // 为新行的删除按钮添加事件监听器
    const deleteBtn = newRow.querySelector('.delete-row');
    deleteBtn.addEventListener('click', function() {
        deleteRow(this);
    });
    
    // 为新行的输入框添加事件监听器
    const inputs = newRow.querySelectorAll('input');
    inputs.forEach(input => {
        input.addEventListener('input', updateMetadataJson);
    });
}

// 删除行
function deleteRow(button) {
    const row = button.closest('tr');
    const tbody = row.parentNode;
    
    // 如果只有一行，则清空输入而不是删除行
    if (tbody.children.length === 1) {
        const inputs = row.querySelectorAll('input');
        inputs.forEach(input => input.value = '');
    } else {
        row.remove();
    }
    
    updateMetadataJson();
}

// 将表格数据转换为JSON
function updateMetadataJson() {
    const rows = document.querySelectorAll('.metadata-row');
    const metadata = {};
    let isValid = true;
    
    rows.forEach(row => {
        const keyInput = row.querySelector('.metadata-key');
        const valueInput = row.querySelector('.metadata-value');
        const key = keyInput.value.trim();
        const value = valueInput.value.trim();
        
        if (key) {
            // 检查键是否重复
            if (metadata.hasOwnProperty(key)) {
                isValid = false;
                keyInput.classList.add('border-red-500');
            } else {
                keyInput.classList.remove('border-red-500');
                metadata[key] = value;
            }
        }
    });
    
    if (isValid) {
        metadataInput.value = Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : '{}';
        metadataError.classList.add('hidden');
    } else {
        metadataError.textContent = '存在重复的键名，请修正';
        metadataError.classList.remove('hidden');
    }
    
    return isValid;
}

// 从JSON加载数据到表格
function loadMetadataFromJson() {
    try {
        // 清空现有表格行
        const tbody = metadataTable.querySelector('tbody');
        tbody.innerHTML = '';
        
        // 解析JSON
        let metadata = {};
        try {
            metadata = JSON.parse(metadataInput.value || '{}');
        } catch (e) {
            console.error('解析元数据JSON失败:', e);
            metadata = {};
        }
        
        // 添加表格行
        const entries = Object.entries(metadata);
        if (entries.length === 0) {
            // 如果没有数据，添加一个空行
            addNewRow();
        } else {
            // 添加数据行
            entries.forEach(([key, value]) => {
                addNewRow(key, value);
            });
        }
        
        metadataError.classList.add('hidden');
    } catch (e) {
        console.error('加载元数据失败:', e);
        // 添加一个空行
        addNewRow();
        metadataError.textContent = '元数据格式有误，已重置';
        metadataError.classList.remove('hidden');
    }
}

// 为添加行按钮添加事件监听器
addRowBtn.addEventListener('click', function() {
    addNewRow();
});

// 表单提交前验证
form.addEventListener('submit', function(e) {
    if (!updateMetadataJson()) {
        e.preventDefault();
        metadataError.classList.remove('hidden');
    }
});

// 添加重新加载元数据按钮
document.addEventListener('DOMContentLoaded', function() {
    const reloadButton = document.createElement('button');
    reloadButton.type = 'button';
    reloadButton.className = 'mt-2 text-xs text-primary hover:text-primary/80 mr-2';
    reloadButton.textContent = '重新加载元数据';
    reloadButton.onclick = loadMetadataFromJson;
    
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'flex justify-start mt-1';
    buttonContainer.appendChild(reloadButton);
    
    const metadataErrorElement = document.getElementById('metadata-error');
    metadataErrorElement.parentNode.insertBefore(buttonContainer, metadataErrorElement);
});

// 初始化：加载元数据到表格
document.addEventListener('DOMContentLoaded', loadMetadataFromJson);
</script>
{% endblock %}